# @Time    : 2024/1/30 21:42
# @Author  : 🍁
# @File    : wiki.py
# @Software: PyCharm
from django.shortcuts import render, redirect
from django import http
from django.urls import reverse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

from web.forms.manage import WikiModelForm
from web import models
from web.utils.scrypty import uid
from web.utils.cos.cos import upload_file


# wiki 首页展示
class WikiView(View):
    # wiki 首页展示
    def get(self, request, project_id):
        wiki_id = request.GET.get("wiki_id")
        if wiki_id:
            if wiki_id.isdecimal():  # 判断wiki_id 是否是数字
                wiki_object = models.Wiki.objects.filter(project_id=request.tartec.project.id, id=wiki_id).first()
                return render(request, "wiki.html", {"wiki_object": wiki_object})
        return render(request, "wiki.html")


# 添加项目
class AddWikiView(View):
    def get(self, request, project_id):
        form = WikiModelForm(request)
        return render(request, "wiki_form.html", {"form": form})

    def post(self, request, project_id):
        form = WikiModelForm(request, data=request.POST)
        if form.is_valid():
            if form.instance.parent_id:  # 判断用户是否选择了父目录
                # 拿到当前项目的父目录对象
                # 让项目的深度是其父目录的深度 + 1
                # 添加深度
                form.instance.depth = form.instance.parent_id.depth + 1
            else:
                form.instance.depth = 1

            # 添加项目id
            form.instance.project_id = request.tartec.project
            form.save()
            # 拿到当前Wiki 的url
            url = reverse("wiki", kwargs={"project_id": request.tartec.project.id})
            # 拼接一下url，使其变成修改wiki 完成之后的url
            preview_url = "{0}?wiki_id={1}".format(url, form.instance.id)
            return redirect(preview_url)

        return http.JsonResponse({"status": False, "error": "添加失败，请重试"})


# 修改wiki 文章
class UpdateWikiView(View):
    def get(self, request, project_id, update_id):
        update_object = models.Wiki.objects.filter(project_id=project_id, id=update_id).first()
        # 判断是否有这个对象
        if not update_object:
            url = reverse("wiki", kwargs={"project_id": request.tartec.project.id})
            return redirect(url)
        form = WikiModelForm(request, instance=update_object)
        return render(request, "wiki_form.html", {"form": form})

    def post(self, request, project_id, update_id):
        update_object = models.Wiki.objects.filter(project_id=project_id, id=update_id).first()
        # 判断是否有这个对象
        if not update_object:
            url = reverse("wiki", kwargs={"project_id": request.tartec.project.id})
            return redirect(url)
        form = WikiModelForm(request, data=request.POST, instance=update_object)
        if form.is_valid():
            if form.instance.parent_id:  # 判断用户是否选择了父目录
                # 拿到当前项目的父目录对象
                # 让项目的深度是其父目录的深度 + 1
                # 添加深度
                form.instance.depth = form.instance.parent_id.depth + 1
            else:
                form.instance.depth = 1
            form.save()  # 保存修改的数据
            # 拿到当前Wiki 的url
            url = reverse("wiki", kwargs={"project_id": request.tartec.project.id})
            # 拼接一下url，使其变成修改wiki 完成之后的url
            preview_url = "{0}?wiki_id={1}".format(url, update_id)
            return redirect(preview_url)
        return render(request, "wiki_form.html", {"form": form})


# 删除wiki 文章
class DeleteWikiView(View):
    def get(self, request, project_id, delete_id):
        # 删除wiki
        try:
            models.Wiki.objects.filter(id=delete_id, project_id=project_id).delete()
            url = reverse("wiki", kwargs={"project_id": project_id})
            return redirect(url)
        except:
            return http.HttpResponseForbidden("删除失败")


# 项目目录展示
class WikiCatalogView(View):
    def get(self, request, project_id):
        # 在数据库中获取当前项目的所有标题已经
        # 取出来是一个Queryset 类型的数据，需要将Queryset类型转换成其他类型方便转换成Json 格式
        data = models.Wiki.objects.filter(project_id=request.tartec.project.id).values("id", "title",
                                                                                       "parent_id").order_by("depth",
                                                                                                             "id")
        return http.JsonResponse({"status": True, "data": list(data)})


# wiki 上传图片
class WikiUploadView(View):
    # 在类视图里面免去CSRF 验证，需要重写dispatch 方法
    # 在函数视图直接使用即可免去验证，不用重写
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, project_id):
        # 允许同源iframe加载
        settings.X_FRAME_OPTIONS = 'SAMEORIGIN'
        # 用户上传的图片对象
        file_object = request.FILES.get("editormd-image-file")
        result = {
            'success': 0,
            'message': None,
            'url': None
        }
        if not file_object:
            result["message"] = "该文件不存在"
            return http.JsonResponse(result)
        # 拿到图片后缀
        ext = file_object.name.split(".")[-1]
        key = "{0}.{1}".format(uid(request.tartec.user.mobile), ext)
        img_url = upload_file(
            bucket=request.tartec.project.bucket,
            region=request.tartec.project.region,
            body=file_object,
            key=key
        )
        result["success"] = 1
        result["url"] = img_url
        print(result["url"])
        return http.JsonResponse(result)
